<template>
  <view class="milestones" :class="isLockScroll?'lockScroll':''">
    <view class="power-tab">
      <view :class="`power-tab-item bg-line-color ${tabIndex == index?'power-tab-item-active':''}`" @click="changeTab(index)" v-for="(item , index) in powerTabs" :key="index">
        <view class="power-tab-item-inner">{{ item }}</view>
      </view>
    </view>
    <view v-if="tabIndex == 0" class="power-body">
      <view class="power-label" style="background-image:url(https://wx.sijiyoufu.com/static/imgs/project/power_share_poi.png)"></view>
      <template v-for="(item,index) in cinemaActivity" :key="index">
        <view class="power-desc" v-if="item.value">{{item.key}}：{{item.value}}</view>
      </template>
      <view class="power-button bg-line-color" @click="powerDialog">
        <view class="power-button-inner">
          <text style="margin-right:12px;">选择场次</text><uv-icon name="arrow-down"></uv-icon>
        </view>
      </view>
      
      <template v-if="Opi.opiid">
        <view class="power-cinema-name">{{ Opi.cinemaName }}</view>
        <view class="power-leave">
          <image :src="trophyIconActive" mode="aspectFit" />
          {{ Opi.playTimeText[0] }} {{ Opi.playTimeText[1] }} {{ Opi.playTimeText[3] }}
        </view>
      </template>
      
      <view class="flex-betenwen">
        <view class="power-button power-button-fill bg-line-color" @click="powerShare" style="width:100%;">
          <view class="power-button-inner">
            分享助力
          </view>
        </view>
      </view>

    </view>
    <view v-else class="power-body">
      <view class="power-register">
        <view class="title">申请信息</view>
        <uv-form labelPosition="left" :model="register" :rules="rules" ref="form">
          <uv-form-item label="选择城市" prop="pickerValue" borderBottom labelWidth="72" @click="openChoose">
            <uv-input v-model="pickerText" border="none" placeholder="请选择城市" :readonly="true">
            </uv-input>
            <template v-slot:right>
              <uv-icon size="13" name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item label="放映日期" prop="playDate" borderBottom labelWidth="72" @click="datetimePicker.open()">
            <uv-input v-model="register.playDate" border="none" placeholder="请选择日期" :readonly="true">
            </uv-input>
            <template v-slot:right>
              <uv-icon size="13" name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item label="放映时段" prop="playTime" borderBottom labelWidth="72" @click="actionSheet.open()">
            <uv-input v-model="register.playTime" border="none" placeholder="请选择时段" :readonly="true">
            </uv-input>
            <template v-slot:right>
              <uv-icon size="13" name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item label="场次形式" prop="edition" borderBottom labelWidth="72" @click="teamPopupRef.open()">
            <uv-input v-model="register.edition" border="none" placeholder="请选择战队" :readonly="true">
            </uv-input>
            <template v-slot:right>
              <uv-icon size="13" name="arrow-right"></uv-icon>
            </template>
          </uv-form-item>
          <uv-form-item label="其它说明" prop="remark" borderBottom labelWidth="72">
            <uv-input v-model="register.remark" placeholder="填写备注" border="none">
            </uv-input>
          </uv-form-item>
          <uv-form-item label="微信号码" prop="wxId" borderBottom labelWidth="72">
            <uv-input v-model="register.wxId" placeholder="填写微信号码" border="none">
            </uv-input>
          </uv-form-item>
          <uv-form-item label="联系电话" prop="mobile" borderBottom labelWidth="72">
            <uv-input v-model="register.mobile" placeholder="填写联系电话" border="none">
            </uv-input>
          </uv-form-item>
        </uv-form>
        <view class="flex-center">
          <view class="power-button power-button-fill bg-line-color" @click="exGroupPower">
            <view class="power-button-inner">
              提交报名
            </view>
          </view>
        </view>
      </view>
    </view>
    <uv-popup ref="popupRef" round="12" mode="bottom" 
      custom-style="height: 46vh;" 
      bgColor="#f5f5f5" 
      :closeable="true"
      @change="toggleLock"
      closeIconPos="top-right">
      <view style="padding:32rpx;font-weight: 600;">选择场次</view>
      <view style="width:100%;height:calc(46vh - 52rpx);overflow: hidden;overflow-y: auto;">
        <uv-radio-group v-model="Opi.opiid">
          <view class="movie_session-item--wrap" v-for="(opi,index) in OpiArr" :key="index" @click="opiChange(opi)">
              <view class="fx-center-middle">
                  <text class="info_time">{{opi.playTimeText[1]}}</text>
                  <text class="fc-tips">{{opi.playTimeText[0]}} {{opi.playTimeText[3]}} </text>
              </view>
              <view class="fx-center-middle">
                  <text class="van-ellipsis">{{opi.cinemaName}}</text>
                  <text class="fc-tips">{{opi.roomName}} {{opi.edition}}</text>
              </view>
              <view class="fx-center-middle">
                <uv-radio shape="circle" @click="opiChange(opi)" :name="opi.opiid" label=""></uv-radio>
              </view>
          </view>
        </uv-radio-group>
      </view>
		</uv-popup>
    <uv-picker ref="picker" round="12" :columns="addressList" :loading="loading" keyName="name" @change="change" @confirm="confirmChange">
		</uv-picker>
    <uv-datetime-picker round="12" ref="datetimePicker" v-model="datetime" mode="date" @confirm="dateconfirm">
		</uv-datetime-picker>
    <uv-action-sheet 
      round="12"
      ref="actionSheet"
      :actions="timelist" 
      title="选择时段"
      @select="selectTime">
		</uv-action-sheet>
    <uv-modal ref="dialogRef"
      :closeOnClickOverlay='false'
      :showConfirmButton="true"
      confirmText="立即获取"
      :showCancelButton="true"
      @confirm="powerConfirm"
    >
      <view class="power-ex">
        <image :src="trophyIconActive" mode="aspectFit" />
        <view class="power-count">还没有可助力场次，获取方式</view>
          <uv-steps :customStyle="{width:'100%'}" current="0">
            <uv-steps-item title="选择影院" desc=""></uv-steps-item>
            <uv-steps-item title="选择场次" desc=""></uv-steps-item>
            <uv-steps-item title="确认选座" desc=""></uv-steps-item>
          </uv-steps>
      </view>
    </uv-modal>
    <uv-popup ref="teamPopupRef" round="12" mode="bottom" 
            custom-style="height: 72vh;" 
            bgColor="#f5f5f5" 
            @change="toggleLock"
            :closeable="true"
            closeIconPos="top-right">
            <Team :isLink="false" @change="changeTeam"/>
		</uv-popup>
    <Tabbar index="3"/>
  </view>
</template>

<script setup lang="ts">
const app = getApp()
import { ref,computed , getCurrentInstance} from 'vue'
import { useUCenterStore } from '@/stores/uCenter'
import Tabbar from '@/components/tabbar'
import { onLoad , onShow} from "@dcloudio/uni-app"
import { province } from '@/api/baseData'
import { getMovieOrderList } from "@/api/movie"
import trophyIconActive from '@/static/trophyActive.svg'
import Team from '@/components/power/team.vue'
const store = useUCenterStore()
const member = computed(() => {
  return store.memberInfo
})
import {  wzCinemaDetaill , applyGroup} from "@/api/baseData"
const Opi = ref<any>({})
const OpiArr = ref<any>([])
const powerTabs = ref<any>(['为场次助力','发起成团'])
const tabIndex = ref<any>(0)
const dialogRef = ref()
const changeTab = (index : any) => {
  tabIndex.value = index
}
const teamPopupRef = ref()
const pickerText = ref<any>('')
const actionSheet = ref()
const datetime = ref<any>(`2024-${new Date().getMonth() + 1}-${new Date().getDate()}`)
const datetimePicker = ref()
const timelist = ref<any>([{name:'上午10:0-12:00'},{name:'下午 12:00-18:00'},{name:'晚上 18:00-22:00'}])
const selectTime = (e:any) => {
  register.value.playTime = e.name
}
const opiChange = (e : any) => {
  Opi.value = e
  popupRef.value.close()
}
const register = ref<any>({
  provinceName:'',
  cityName:'',
  pickerValue:'',
  playDate:'',
  playTime:'',
  edition:'',
  remark:'',
  wxId:'',
  mobile:'',
})
const rules = ref<any>({
    'mobile': {
        type: 'string',
        required: true,
        message: '请填写联系电话',
        trigger: ['blur', 'change']
    },
})

const picker = ref()
const provinces = ref<any>([])//省
const citys = ref<any>([])//省
const areas = ref<any>([])//省
const loading = ref<any>(false)
const defaultValue = ref<any>([11, 110100, 19])
const addressList = computed(() => {
    return [provinces.value, citys.value];
})
const dateconfirm = (e : any) => {
  const date = new Date(e.value)
  register.value.playDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
const change = (e : any) => {
    if (loading.value) return;
    const { columnIndex, index, indexs } = e
    // 改变了省
    if (columnIndex === 0) {
        citys.value = provinces.value[index]?.cityList || []
        areas.value = citys.value[0]?.countyList || []
        picker.value.setIndexs([index, 0, 0],true)
    } else if (columnIndex === 1) {
        areas.value = citys.value[index]?.countyList || []
        picker.value.setIndexs(indexs,true)
    }
}
const handlePickValueDefault = () => {
    const _pickerValue = []
    // 设置省
    _pickerValue[0] = provinces.value.findIndex(item => Number(item.provincecode) === defaultValue.value[0]);
    // 设置市
    citys.value = provinces.value[_pickerValue[0]]?.cityList || [];
    _pickerValue[1] = citys.value.findIndex(item => Number(item.citycode) === defaultValue.value[1]);
    // 设置区
    areas.value = citys.value[_pickerValue[1]]?.countyList || [];
    _pickerValue[2] = areas.value.findIndex(item => Number(item.countycode) === defaultValue.value[2]);

    // 重置下位置
    picker.value.setIndexs([_pickerValue[0], _pickerValue[1], _pickerValue[2]],true);
    register.value.pickerValue = _pickerValue
}
const openChoose = () => {
    picker.value.open();
    handlePickValueDefault()
}
const confirmChange = (e : any) => {
  register.value.provinceName = e.value[0].name
  register.value.cityName = e.value[1].name
  defaultValue.value = register.value.pickerValue = [e.value[0].provincecode,e.value[1].citycode]
  pickerText.value = `${e.value[0].name}/${e.value[1].name}`
}

const isLockScroll = ref<any>(false)
const toggleLock = (e : any) => {
  isLockScroll.value = e.show
}
const popupRef = ref()
const powerDialog = () => {
  getMyPowers(true,() => {
    if(hasPower())popupRef.value.open()
  })
}

const hasPower = () => {
  if(OpiArr.value.length == 0){
    dialogRef.value.open()
    return false
  }else return true
}

const exPower = () => {
  if(!checkLogin())return ;
  if(hasPower()){
    uni.navigateTo({
        url:`/pages/movie/resolveSeats?opiid=${Opi.value.opiid?Opi.value.opiid:OpiArr.value[0].opiid}`
    })
  }
}

const changeTeam = (item  : any) => {
  register.value.edition = item.name
  teamPopupRef.value.close()
}

const getMyPowers = (flag : boolean,callback : any) => {
  if(flag && !checkLogin())return ;
  getMovieOrderList({page_no:1,per:20}).then(res => {
    if(res.success){
      const curtime = new Date()
      const temp = []
      const opiMap = {}
      res.data.forEach(item => {
        item.playTimeText = item.playTimeText.split(' ')
        if(curtime < new Date(item.playTime) && !opiMap[item.opiid]){
          temp.push(item)
          opiMap[item.opiid] = item
        }
        // temp.push(item)
      })
      OpiArr.value = temp
      if(!flag && temp.length > 0)Opi.value = temp[0]
      callback()
    }
  })
}

const powerShare = () => {
  if(!checkLogin())return ;
  if(hasPower()){
    uni.setStorage({
      key: 'Opi',
      data: Opi.value
    })
    uni.navigateTo({
      url:'/pages/newLine/share'
    })
  }
}
const checkLogin = () => {
  if(!member.value.mobile){
    //存储当前路由地址，授权完毕回调
    store.$patch((state) => {
        state.redirectPath = '/pages/newLine/milestones'
    })
    uni.navigateTo({
      url: '/pages/auth/index'
    })
    return false
  }else return true
}
const powerConfirm = () => {
  if(!checkLogin())return ;
  uni.reLaunch({
    url: '/pages/movie/index'
  })
}

const exGroupPower = () => {
  const {provinceName,cityName,playDate,playTime,edition,remark,wxId,mobile} = register.value
  if(!provinceName && !cityName){
    uni.showToast({
        icon: 'none',
        title: `请选择一个观影城市！`
    })
    return 
  }
  if(!playDate){
    uni.showToast({
        icon: 'none',
        title: `请选择一个观影日期！`
    })
    return
  }
  if(!playTime){
    uni.showToast({
        icon: 'none',
        title: `请选择一个观影时段！`
    })
    return
  }
  if(!mobile){
    uni.showToast({
        icon: 'none',
        title: `手机号码必填，便于成团后联系你！`
    })
    return
  }
  applyGroup({provinceName,cityName,playDate,playTime,edition,remark,wxId,mobile}).then(res => {
    if(res.success){
      uni.showToast({
          icon: 'success',
          title: "信息提交成功！"
      })
    }else {
      uni.showToast({
          icon: 'none',
          title: res.msg
      })
    }
  })
}

const cinemaActivity = ref<any>([])
onLoad(async (options) => {
  const { proxy } = getCurrentInstance();
  await proxy.$onLaunched;
  wzCinemaDetaill({}).then(res => {
    cinemaActivity.value = res.data
  })
  province({}).then(res => {
      res.data.forEach(province => {
          province.name = province.provincename
          if(province.cityList && province.cityList.length > 0){
              province.cityList.forEach(city => {
                  city.name = city.cityname
                  if(city.countyList && city.countyList.length > 0){
                      city.countyList.forEach(county => {
                          county.name = county.countyname
                      })
                  }
              })
          }
      })
      provinces.value = res.data
      handlePickValueDefault()
  })
  if(options.tabIndex)tabIndex.value = options.tabIndex
})

onShow(() => {
  getMyPowers(false,() => {})
})
</script>

<style lang="scss">
.milestones{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width:100vw;
  overflow: hidden;
  overflow-y: scroll;
}

.power-tab{
  display: flex;
  justify-content: center;
  align-items: center;
  padding:180upx 52upx 70upx;
}
.power-tab-item,.power-button{
    height: 62upx;
    line-height: 62upx;
    width: 220upx;
    text-align: center;
    padding: 3upx;
    display: flex;
    margin: 0 42upx;
    border-radius: 72upx;
    overflow: hidden;
    .power-tab-item-inner,.power-button-inner{
      width:100%;
      background:#fff;
      color:#333;
      border-radius: 72upx;
    }
    &.power-tab-item-active,&.power-button-fill{
      .power-tab-item-inner,.power-button-inner{
        background:transparent;
        color:#fff;
      }
    }
}
.power-button{
  height: 82upx;
  line-height: 82upx;
  width: 86%;
  margin: 42upx auto;
  color:#000;
  padding:6upx;
  font-size: 32upx;
  font-weight: 600;
  .power-button-inner{
    display: flex;
    align-items: center;
    justify-content: center;
    .uv-icon{
      margin-right: 32upx;
    }
  }
}
.power-body{
  padding:0 32upx 32upx;
  width:100%;
  box-sizing: border-box;
  color:#fff;
  .power-label{
    width:100%;
    height:163upx;
    background-position: center;
    background-size:cover;
    margin:0 auto 52upx;
  }
  .power-desc{width:72%;margin:16upx auto;}
}
.power-cinema-name{
  font-weight: 600;
  font-size:42upx;
  padding:0 0 22upx;
  text-align: center
}

.power-leave{
  display:flex;
  justify-content: center;
  align-items: center;
  font-size: 42upx;
  font-weight: 600;
  color:rgb(245,238,182);
  image{
    width:36upx;
    height:36upx;
    margin-right: 24upx;
  }
}
.power-total{
  font-size:52upx;
  color:#dec091;
  font-weight: 600;
  position: relative;
  .power-total-line{
    position: absolute;
    right:-52upx;
    bottom: -17px;
    height: 12upx;
    width:92%;
    background:linear-gradient(136deg, transparent 10%, #dec091 100%);
  }
}
.power-list-box{
  padding: 52upx 0 0 0;
  .power-list-item{
    margin-top: 72upx;
    display: flex;
    justify-content: space-between;
    position: relative;
    color: #fff;
    border-radius: 52upx;
    .textbox{
      padding: 22rpx 22rpx 22rpx 180rpx;
      width: 76%;
      font-size: 26rpx;
    }
    .imagebox{
      width: 160rpx;
      height: 160rpx;
      position: absolute;
      top: 50%;
      left: -9rpx;
      transform: translateY(-50%);
      image{
        width: 160upx;
        height: 160upx;
        border-radius: 204upx;
      }
    }
    .actorImageBox{
      bottom: -19rpx;
      left: -19rpx;
    }
    .power-status{
      position: absolute;
      right: -6px;
      bottom: -18upx;
      width: 106upx;
      height: 106upx;
      border-radius: 72upx;
    }
  }
}
.flex-betenwen{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding:0 32upx 32upx;
  .power-button{
    width:42%;
  }
}
.power-actor-body{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin-bottom: 52upx;
  .actor-header{
    width:calc(100vw / 4);
    height:calc(100vw / 4);
    border-radius: 200rpx;
    margin-bottom: 32upx;
  }
  .actor-name{
    color:#000;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text{
      font-weight: 600;
      font-size: 32upx;
    }
  }
}
.power-ex{
  display:flex;
  flex-direction: column;
  align-items: center;
  padding:52upx 0;
  width:100%;
  image{
    width:160upx;
    height:160upx;
  }
  .power-count{
    padding:32rpx 0 52rpx;
    color:rgb(245,238,182);
    font-size:32upx;
    font-weight: 600;
  }
  .minus {
		width: 28px;
		height: 28px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
	.input {
		padding: 0 10px;
	}
	.plus {
		width: 28px;
		height: 28px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
}
.lockScroll{
  overflow: hidden;
	position: fixed;
}
.power-register{
  width: 88%;
  margin: 0 auto;
  border-radius: 12upx;
  background-color: #fff;
  padding: 32upx;
  .title{
    padding:12upx;
    text-align: center;
  }
}
.movie_session-item--wrap {
    display: grid;
    grid-template-columns: 32% 56% 12%;
    padding: 8px 0;
    margin: 6px 0;
    position:relative;
    border-bottom: 1px solid rgba(0,0,0,.1);
    width:100%;
    > view {
        > text {
            display: inline-block;
            padding: 1px 0;
            width: 100%;
            text-align: center;
            text-overflow: ellipsis;
            overflow: hidden;
            height: 18px;
        }
        &.price_remark text {
            padding: 0;
        }

        .info_time {
            font-weight: 700;
            color: #000000;
            font-size:42upx;
            line-height: 1;
        }

        .price-grid {
            display: grid;
            grid-template-columns: auto auto;
            align-items: center;
            justify-items: end;
            gap: 0 5px;
            
            .sheng {
                padding: 1px 4px;
                background-color: #f5b225;
                color: #fff;
            }
        }
    }
}
</style>
